package com.navinfo.platform.trip.common.arithmetic;

import com.navinfo.platform.trip.common.arithmetic.annotation.Arithmetic;
import com.navinfo.platform.trip.common.arithmetic.data.CommonData;
import com.navinfo.platform.trip.common.arithmetic.data.OuterStatisticData;
import com.navinfo.platform.trip.common.arithmetic.manager.AbstractArithmetic;
import com.navinfo.platform.trip.common.arithmetic.var.VarBrakeHighSpeed;
import com.navinfo.platform.trip.common.config.ConfigMap;
import com.navinfo.platform.trip.common.util.ArithmeticUtils;

import java.math.BigDecimal;

/**
 * 高速刹车算法<br/>
 * 依赖{@link Mileage}里程油耗算法<br/>
 * 输出：统计<br/>
 */
@Arithmetic(name = "高速刹车统计")
public class BrakeHighSpeed extends AbstractArithmetic<VarBrakeHighSpeed> {
    /**
     * 高速刹车，速度阀值
     */
    private double speedThreshold0 = ArithmeticUtils.speedKmhToMs(ConfigMap.getInteger("HighSpeedBrake_speed_min"));

    /**
     * 是否高速刹车
     * @param brakeState
     * @param speedMs
     * @return
     */
    private boolean isState(boolean brakeState, BigDecimal speedMs) {
        if (speedMs == null) {
            return false;
        }
        return brakeState && speedMs.doubleValue() > speedThreshold0;
    }

    @Override
    public void calculate() {
        logger.debug("进入高速刹车统计算法.");
        VarBrakeHighSpeed var = getObj();
        CommonData data = getCommonData();

        boolean preStatus = var.isPreState();
        boolean curStatus = isState(data.isBrake(), data.getSpeedMs());
        logger.debug("高速刹车统计，状态：pre:{},current:{}", preStatus, curStatus);

        switch (getEventStatus(preStatus, curStatus)) {
            case START:
                logger.debug("高速刹车统计，事件开始.");
                var.setNumber(var.getNumber() + 1);
                break;
            case IN:
                logger.debug("高速刹车统计，事件中.");
                var.setMileage(var.getMileage() + data.getDffMileage());
                var.setTimeMs(var.getTimeMs() + data.getDffTime());
                break;
            case END:
                logger.debug("高速刹车统计，事件结束.");
                var.setMileage(var.getMileage() + data.getDffMileage());
                var.setTimeMs(var.getTimeMs() + data.getDffTime());
                break;
            default:
                logger.debug("高速刹车统计，状态：上一次和本次都未高速刹车，跳出算法.");
                break;
        }

        //设置上一个点状态、供下个点计算
        var.setPreState(curStatus);
        logger.debug("高速刹车统计算法结束.");
    }

    @Override
    public void collect(OuterStatisticData statisticDataOut) {
        VarBrakeHighSpeed var = super.getObj();
        statisticDataOut.setHsbNumber(var.getNumber());
        statisticDataOut.setHsbMileage(ArithmeticUtils.mileageMToM(var.getMileage()));
        statisticDataOut.setHsbDuration(ArithmeticUtils.timeMsToSecond(var.getTimeMs()));

       /* //实时计算，增加刹车次数
        statisticDataOut.setBrakeTimes_DF(Optional.ofNullable(statisticDataOut.getBrakeTimes_DF()).orElse(0)+var.getNumber());*/
    }
}
